package com.hxd.mall.module.usercenter.settings

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.hxd.mall.BuildConfig
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_is_use
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_name
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.WX_PackageName
import com.hxd.mall.constant.HxdConstantsAccount
import com.hxd.mall.constant.HxdConstantsNet.HOST_URL_ONLINE
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.PathUserCenter.path_user_center_alipay_bind
import com.hxd.mall.constant.HxdConstantsRouterPath.PathUserCenter.path_user_center_setting
import com.hxd.mall.module.EventBean
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.account.bean.ServiceFlag
import com.hxd.mall.module.usercenter.settings.bean.SettingBean
import com.hxd.mall.utils.local.ActivityUtil
import com.hxd.mall.utils.local.ActivityUtil.sendEventBus
import com.hxd.mall.utils.local.HxdSharePreferenceUtil
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil.closeOtherOnlyActivity
import com.hxd.mall.utils.local.ThirdInitUtil.hostChange
import com.hxd.mall.utils.open.*
import com.hxd.mall.utils.open.DataCleanManager.cleanCache
import com.hxd.threelibrary.baichuan.ShoppingUtils
import com.hxd.threelibrary.weChat.WeChatUtils
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import crossoverone.statuslib.StatusUtil
import kotlinx.android.synthetic.main.activity_user_center_layout.*
import kotlinx.android.synthetic.main.base_title.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*

/**
 * 设置页
 */
@Route(path = path_user_center_setting)
class SettingsActivity : BaseInjectActivity<ISettingsPresenter>(), ISettingsView {

    private var mBean: SettingBean? = null

    override fun attachLayoutRes(): Int = R.layout.activity_user_center_layout

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        setTitleCommon(getString(R.string.setting))

        /**
         * 服务域名切换
         */
        if (BuildConfig.DEBUG) {
            layout_base_title_second.setOnLongClickListener {
                val array = arrayOf(
                    "http://172.20.168.40:8087", "http://172.20.169.239:8087",
                    "http://mall-beta.hxvc.com", "https://mall.hxvc.com",
                    "http://mall-stg.hxvc.com"
                )
                val index = array.indexOfFirst { it == HOST_URL_ONLINE }
                showDialogSingChoic(this, "服务域名切换", array, index) {
                    ActivityUtil.clearUserInfo()
                    hostChange(array[it])

                    closeOtherOnlyActivity(MainActivity(), path_login_input_phone)
                    sendEventBus(EventBean(0))
                    routerNavigation(path_login_input_phone)
                }
                false
            }
        }

        tv_version.text = "v${BuildConfig.VERSION_NAME}"

        addSetOnClickListener(clear_cash, taobaoAuth, avatar, alipayAuth, nick, logout, user, person, wx_layout) {
            onClick(it)
        }
        EventBus.getDefault().register(this)
    }

    private fun onClick(it: View) {
        when (it) {
            clear_cash -> {
                cleanCache(this)
                cash.post {
                    cash.text = "0 KB"
                    setgrayBg()
                }
            }
            taobaoAuth -> {
                if (tb_state.text.toString() == "已授权") return
                showConfirmWithTitleDialog("提示", "确定取消淘宝授权吗？", "") {
                    //未授权 需要授权
                    EventBus.getDefault().post("1")
                }
            }
            avatar -> {
//                choosePic(imagePickerCode, cameraPickerCode)
            }
            alipayAuth -> {
                routerNavigation(path_user_center_alipay_bind)
            }
            nick -> {
                // routerNavigation(path_user_center_nick)
            }
            logout -> {
                mPresenter?.logout()
            }

            user -> {
                routerNavigation(path_to_webview, mutableMapOf(key_web_url to "https://www.hxvc.com/agreement.html", key_title_name to "用户协议", key_title_is_use to true))
            }

            person -> {
                routerNavigation(path_to_webview, mutableMapOf(key_web_url to "https://www.hxvc.com/privacy.html", key_title_name to "隐私协议", key_title_is_use to true))
            }
            wx_layout -> {
                //微信绑定
                if(!ShoppingUtils.checkPackage(this, WX_PackageName)){
                    //如果没有安装微信
                    ToastUtil.showToast("您未安装微信")
                    return
                }
                if (mBean?.data?.isWxAuthed==true)
                    ToastUtil.showToast("您已授权过微信")
                else
                    bindWeChat()
            }
        }
    }

    //绑定微信
    private fun bindWeChat() {
        mPresenter?.getflag()

    }

    override fun initData() {
        cash.text = DataCleanManager.getCacheSize(this)
        if ("0 KB" == cash.text.toString().trim()) {
            setgrayBg()
        } else {
            clear_cash.setBackgroundDrawable(resources.getDrawable(R.drawable.dialog_bg_red_line))
            clear_cash.setTextColor(resources.getColor(R.color.color_E24840))
        }
        mPresenter?.getData()
    }

    private fun setgrayBg() {
        clear_cash.setBackgroundDrawable(resources.getDrawable(R.drawable.shape_btn_orange_ring_bg))
        clear_cash.setTextColor(resources.getColor(R.color.color_999999))
    }


    //获取数据
    override fun showData(t: SettingBean) {
        if (null == t) return
        mBean = t
        showView()
    }

    //界面数据展示
    private fun showView() {
        iv_head.loadCircle(mBean?.data?.avatarUrl)
        tv_nick.text = mBean?.data?.nickname
        mBean?.data?.isIsTbAuthed?.let {
            if (it) {
                tb_state.text = "已授权"
                tb_state.setTextColor(resources.getColor(R.color.color_999999))
            } else {
                tb_state.text = "未授权"
                tb_state.setTextColor(resources.getColor(R.color.color_E24840))
            }
        }
        mBean?.data?.isWxAuthed?.let {
            if (it) {
                bind_wx.text = "已绑定"
                bind_wx.setTextColor(resources.getColor(R.color.color_999999))
            } else {
                bind_wx.text = "立即绑定"
                bind_wx.setTextColor(resources.getColor(R.color.color_E24840))
            }
        }

    }

    override fun setStatusColor() {
        StatusUtil.setUseStatusBarColor(this, Color.WHITE)
    }

    override fun setSystemInvadeBlack() {
        StatusUtil.setSystemStatus(this, false, true)
    }

    override fun fetchFlag(t: ServiceFlag) {
        if (null == t) return
        //从微信获取code,然后把code值传递给后端进行请求
        t.data?.state?.let { HxdSharePreferenceUtil.saveStringData(HxdConstantsAccount.wx_login_flag, it) }
        WeChatUtils().regToWx(this, t?.data?.scope, t?.data?.state)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null) {
                val images =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                iv_head.loadCircle(images[0].path)
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun updataWxAuther(event:SettingBean){
        bind_wx.text = "已绑定"
        bind_wx.setTextColor(resources.getColor(R.color.color_999999))
    }
}
